﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Yahoo.Yui.Compressor;

namespace InteSoft.Web.ExternalResourceLoader
{
    public class CSSMinify
    {
        public static string Minify(UrlHelper urlHelper, string cssPath, string requestPath, string css)
        {
            return Minify(urlHelper, cssPath, requestPath, css, 0);
        }

        public static string Minify(UrlHelper urlHelper, string cssPath, string requestPath, string css, int columnWidth)
        {
            css = Yahoo.Yui.Compressor.CssCompressor.Compress(css, columnWidth, CssCompressionType.MichaelAshRegexEnhancements);

            // this construct is to enable us to refer to the relativePath above ...
            var urlDelegate = new MatchEvaluator(delegate (Match m)
                {
                    // Change relative (to the original CSS) URL references to make them relative to the requested URL (controller / action)
                    var url = m.Value;

                    var uri = new Uri(url, UriKind.RelativeOrAbsolute);
                    
                    if (uri.IsAbsoluteUri || VirtualPathUtility.IsAbsolute(url))
                    {
                        // if the URL is absolute ("http://server/path/file.ext") or app absolute ("/path/file.ext") then leave it as it is
                    } 
                    else
                    {
                        // url is relative to css ... we want to make it absolute
                        url = VirtualPathUtility.Combine(cssPath, url);
                        // url = VirtualPathUtility.MakeRelative(requestPath, url);

                        // use ExContent here
                        url = urlHelper.ExContent(url);
                    }

                    return url;
                });

            // replace URLs
            css = Regex.Replace(css, @"(?<=url\(\s*([""']?))(?<url>.+?)(?=\1\s*\))", urlDelegate, RegexOptions.IgnoreCase);
            css = Regex.Replace(css, @"(?<=@import\s*([""']))(?<url>.+?)(?=\1\s*;)", urlDelegate, RegexOptions.IgnoreCase);

            return css;
        }
    }
}